import datetime
import re
from collections import OrderedDict

import matplotlib.pyplot as plt


def parse_log(filename):
    pattern = re.compile(r'\[((\d\d:\d\d:\d\d).\d)\d\d\].+')
    stats = OrderedDict()
    start = ""
    end = ""
    with open(filename, 'r') as f:
        start = pattern.match(f.readline()).group(2)
        start = datetime.datetime.strptime(start, "%H:%M:%S")
        for line in f.readlines():
            pass
        end = pattern.match(line).group(2)
        end = datetime.datetime.strptime(end, "%H:%M:%S") + datetime.timedelta(seconds=2)

        while (end - start).seconds > 0:
            stats[start.strftime("%H:%M:%S.%f")[:-5]] = 0
            start += datetime.timedelta(milliseconds=100)

        f.seek(0)
        for line in f.readlines():
            match = pattern.match(line)
            stats[match.group(1)] += 1

    return stats


if __name__ == '__main__':
    stats = parse_log("limiter.log")
    requests = []

    for _, v in stats.items():
        requests.append(v)

    plt.plot(list(range(len(requests))), requests)
    plt.xlabel("TimeUnit(100ms)")
    plt.ylabel("Requests")
    plt.show()
